package com.dagene.weixin.util;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;

import java.io.File;
import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;

import com.dagene.weixin.bean.AccessToken;

/**
 * 上传下载多媒体文件类
 * 
 * @author zhaomy
 * @date: 2015-12-16 上午9:37:29
 */
public class MediaUtil {
	// 下载多媒体文件接口
	static String downloadUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
	// 获取用户基本信息接口
	static String userInfoUrl ="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	/**
	 * 模拟form表单的形式 ，上传文件 以输出流的形式把文件写入到url中，然后用输入流来获取url的响应
	 * 
	 * @param url
	 *            请求地址 form表单url地址
	 * @param filePath
	 *            文件在服务器保存路径
	 * @return String 返回media_id
	 * @throws IOException
	 */
	public static String uploadMedia(String url, String filePath)
			throws Exception {
		String mediaId = StringUtils.EMPTY;

		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {

			throw new IOException("文件不存在");
		}

		// https请求
		String result = new HttpUtil().httpsRequestForMedia(url, file);
		if (result != null) {

			JSONObject jsonObj = JSONObject.fromObject(result);
			if (jsonObj.has("media_id")) {

				mediaId = jsonObj.getString("media_id");
			} else {

				throw new Exception(result);
			}
		} else {

			throw new Exception("获取media_id失败");
		}
		return mediaId;
	}

	/**
	 * 根据media_id获取多媒体文件
	 * 
	 * @param mediaId
	 *            媒体文件id
	 * @param savePath
	 *            文件在服务器上的存储路径
	 */
	public static String downloadMedia(String mediaId, String savePath, String type) {
		
		AccessToken at = new HttpUtil().getAccessToken(Constants.APPID,
				Constants.APPSECRET);
		
		String url = downloadUrl.replace("ACCESS_TOKEN", at.getToken())
				.replace("MEDIA_ID", mediaId);
		System.out.println(mediaId);
		if(type.equals("voice")){
			return new HttpUtil().downloadVoiceFile(url, savePath);
		}else{
			return new HttpUtil().downloadMediaFile(url, savePath);
		}
	}
	
	//将微信生成的amr文件转为mp3文件
  	public static void changeToMp3(String sourcePath, String targetPath) {  
        File source = new File(sourcePath);  
        File target = new File(targetPath);  
        AudioAttributes audio = new AudioAttributes();  
        Encoder encoder = new Encoder();  
  
        audio.setCodec("libmp3lame");  
        EncodingAttributes attrs = new EncodingAttributes();  
        attrs.setFormat("mp3");  
        attrs.setAudioAttributes(audio);  
        try {  
            encoder.encode(source, target, attrs);  
        } catch (IllegalArgumentException e) {  
            e.printStackTrace();  
        } catch (InputFormatException e) {  
            e.printStackTrace();  
        } catch (EncoderException e) {
            //e.printStackTrace();
        }
    }

	// 获取用户基本信息
	public static JSONObject getUserInfo(String openid){
		
		AccessToken at = new HttpUtil().getAccessToken(Constants.APPID,
				Constants.APPSECRET);
		
		String url = userInfoUrl.replace("ACCESS_TOKEN", at.getToken())
				.replace("OPENID", openid);
		
		JSONObject ret = new HttpUtil().httpGetRequest(url, "GET");
		
		if (ret.has("subscribe")){
			return ret;
		} else {
			HttpUtil.setAccessToken(null);
			at = new HttpUtil().getAccessToken(Constants.APPID,
					Constants.APPSECRET);
			
			url = userInfoUrl.replace("ACCESS_TOKEN", at.getToken())
					.replace("OPENID", openid);
			
			return new HttpUtil().httpGetRequest(url, "GET");
		}
		
				
	}
}
